/*
 * @lc app=leetcode.cn id=374 lang=typescript
 *
 * [374] 猜数字大小
 */

// @lc code=start
/**
 * Forward declaration of guess API.
 * @param {number} num   your guess
 * @return 	            -1 if num is lower than the guess number
 *			             1 if num is higher than the guess number
 *                       otherwise return 0
 * var guess = function(num) {}
 */
// 二分查找递归法 非常容易出错
var guess: (num: number) => -1 | 0 | 1;
function guessNumber(n: number): number {
    let right = n;
    let left = 1;
    let mid!: number;
    do {
        if (!guess(left)) return left;
        if (!guess(right)) return right;
        let mid = Math.floor((left + right) / 2);
        const result = guess(mid);
        if (result === 0) return mid;

        // TODO 注意题目的意思
        // pick 是目标数， num 是输入数
        // 1 的时候 目标在中心右侧，则移动左侧
        if (result === 1) left = mid + 1;
        if (result === -1) right = mid - 1;
    } while (left < right);
    return mid;
}
// @lc code=end
